package cn.edu.ujs.coor.service;

import cn.edu.ujs.coor.model.Message;
import cn.edu.ujs.coor.repository.message.MessageMapper;
import cn.edu.ujs.coor.repository.message.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息相关Service
 *
 * @author 柳曾雄
 * @date 2018-07-29
 */
@Service
public class MessageService extends BaseService<Message, Message> {

    @Autowired
    public void setMapper (MessageMapper mapper) {
        this.mapper = mapper;
    }

    @Autowired
    public void setRepositoty (MessageRepository repositoty) {
        this.repository = repositoty;
    }

    /**
     * 根据用户编号获取消息列表
     * @param userId
     * @return
     */
    public List<Message> listByUserId (String userId) {
        return ((MessageRepository) repository).findByUserId(userId);
    }

    /**
     * 向用户发送消息
     * @param title
     * @param content
     * @param userId
     */
    public void add (String title, String content, String userId) {
        Message message = Message
                .builder()
                .content(content)
                .userId(userId)
                .title(title)
                .status(Message.UNREAD)
                .build();
        this.save(message);
    }

    /**
     * 向多个用户发送消息
     * @param title
     * @param content
     * @param userIds
     */
    public void add (String title, String content, List<String> userIds) {
        List<Message> list = new ArrayList<>();
        for (String userId : userIds) {
            Message message = Message
                    .builder()
                    .content(content)
                    .userId(userId)
                    .title(title)
                    .status(Message.UNREAD)
                    .build();
            list.add(message);
        }
        this.repository.saveAll(list);
    }

    /**
     * 消息状态设置已读
     * @param messageId
     */
    public void read (String messageId) {
        Message message = findById(messageId);
        message.setStatus(Message.READ);
        save(message);
    }
}